package com.szh.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.szh.common.constant.AuthServerConstant;
import com.szh.common.utils.HttpUtils;
import com.szh.common.utils.R;
import com.szh.gulimall.auth.feign.MemberFeignService;
import com.szh.common.vo.MemberResponseVo;
import com.szh.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 微博社交登录
 *
 * @author: SongZiHao
 * @date: 2023/1/10
 */
@Controller
public class OAuth2Controller {

    private static final Logger LOGGER = LoggerFactory.getLogger(OAuth2Controller.class);

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * OAuth2.0认证Gitee登录
     */
    @GetMapping(value = "/oauth2.0/gitee/success")
    public String giteeLogin(@RequestParam("code") String code, HttpSession session) throws Exception {
        //发送 https://gitee.com/oauth/token 请求所需的参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("client_id", "0d7fce29baf58f25742a3c3d330519fbb4fa4f7607a137391c6b29390ee0c0b2");
//        paramMap.put("client_secret", "5f8cd5cb41b72b52737d73b3b84d29e3782d97f9391c806b6654d788fadab050");
        paramMap.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        paramMap.put("code", code);
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("client_secret", "5f8cd5cb41b72b52737d73b3b84d29e3782d97f9391c806b6654d788fadab050");
        //根据Gitee返回的code值，换取accessToken
        HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post",
                new HashMap<>(), paramMap, bodyMap);
        if (response.getStatusLine().getStatusCode() == 200) { // https://gitee.com/oauth/token请求成功
            //将响应体数据转为json字符串，获取access_token
            String json = EntityUtils.toString(response.getEntity());
            //将json字符串转为SocialUser类型的数据，其中封装了access_token
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
            //所以这里有可能是登录或者注册这个社交用户，远程调用member服务
            R result = memberFeignService.oauthLogin(socialUser);
            if (result.getCode() == 0) {
                MemberResponseVo member = result.getData("data", new TypeReference<MemberResponseVo>() {});
                LOGGER.info("Gitee用户登录成功，用户信息：{}", member);
                //登录成功之后，将用户信息member放到session中，再跳转回首页
                session.setAttribute(AuthServerConstant.SESSION_KEY, member);
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else { // https://gitee.com/oauth/token请求失败
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
